package com.lanou.elh.sso.service.impl;

import com.lanou.elh.sso.entity.Member;
import com.lanou.elh.sso.mapper.MemberMapper;
import com.lanou.elh.sso.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import org.springframework.data.redis.core.StringRedisTemplate;
import com.alibaba.fastjson.JSON;

@Service
public class MemberServiceImpl implements MemberService {
    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Member login(Map<String, Object> map) {
        //通过用户的账号和密码登录
        String pwd = (String) map.get("userPwd");

        // 生成一个MD5加密计算摘要
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(pwd.getBytes());
            String password = new BigInteger(1, md.digest()).toString(16);
            map.put("userPwd", password);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        Member member = memberMapper.findMemberByUsernameAndPassword(map);

        return member;
    }

    @Override
    public String getToken(Map<String, Object> map) {

        String token = UUID.randomUUID().toString();
        Member member = memberMapper.findMemberByUsernameAndPassword(map);
        String jmember = JSON.toJSONString(member);
//      将生成的token存入redis
        stringRedisTemplate.opsForValue().set("token:" + token, jmember);
//       设置失效时间
        stringRedisTemplate.expire("token:" + token, 1800, TimeUnit.MILLISECONDS);
        return token;

    }

    @Override
    public Member getMember(String token) {
        String jmember = stringRedisTemplate.opsForValue().get("token:" + token);
        stringRedisTemplate.expire("token:" + token, 1800, TimeUnit.MILLISECONDS);
        Member member = JSON.parseObject(jmember,Member.class);
        return member;
    }
}
